<!--
 * @author tiancho
 -->
<template>
  <el-container id="setadmin">
    <el-main class="powerallot-main">
      <div class="common-search-inner setAdmin">
        <el-row>
          <el-col :span="6">
            <div class="search-inner-item">
              <div class="item-label">用户名称</div>
              <el-input
                v-model.trim="searchOut.userName"
                style="width: 90%;"
                class="filter-item"
                placeholder="请输入用户名搜索"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-inner-item">
              <div class="item-label">真实姓名</div>
              <el-input
                v-model.trim="searchOut.realName"
                style="width: 90%;"
                class="filter-item"
                placeholder="请输入真实姓名搜索"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-inner-item">
              <div class="item-label">联系电话</div>
              <el-input
                v-model.trim="searchOut.phone"
                style="width: 90%;"
                class="filter-item"
                placeholder="请输入完整的电话号码"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-inner-item">
              <div class="item-label">是否向下兼容</div>
              <el-checkbox-group v-model="searchOut.compatibility" style="margin-top:15px;">
                <el-checkbox
                  v-for="v in dict.SFXXJR"
                  :key="v.dictValue"
                  :label="v.dictValue"
                >{{ v.dictName }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="btns" style="margin-top: 10px">
              <el-button style="margin-bottom: 10px;" size="mini" @click="addUser">添加用户</el-button>
              <el-button style="margin-bottom: 10px;" size="mini" @click="handleDeletes">删除用户</el-button>
            </div>
          </el-col>
          <el-col :span="12" style="margin-bottom:10px;margin-top:10px;text-align:right;">
            <el-button v-waves type="primary" size="mini" @click="handleFilter">搜索</el-button>
            <el-button size="mini" type="primary" @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table
        ref="usertable"
        v-loading="listLoading"
        :data="list"
        class="tableScope"
        height="300px"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userName" label="用户名称" show-overflow-tooltip width="160" />
        <el-table-column prop="realName" label="真实姓名" show-overflow-tooltip />
        <el-table-column prop="phone" label="联系电话" width="140" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.phone?handleDecrypt(scope.row.phone):'' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orgName" label="所属组织" width="200" show-overflow-tooltip />
        <el-table-column prop="compatibilityName" label="权限范围" width="100" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.compatibilityName === '是' ? '向下兼容' : '管理本级' }}</template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="150"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="btn-pagion fix">
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </div>
    </el-main>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :title="'添加用户'"
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
      center
      fullscreen
    >
      <add-user ref="UserResetting" @userData="userData" />
      <div slot="footer" class="dialog-footer">
        <el-checkbox v-model="iscompatibility" style="padding-right:10px;">向下兼容</el-checkbox>
        <el-button style="padding: 8px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-loading.fullscreen.lock="fullscreenLoading"
          style="padding: 8px 30px;"
          type="primary"
          @click="insertUser()"
        >确定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { roleList, queryMenu, userList, saveMenu, deleteUser, insertRoleUser, getDictByCode } from '@/views/organmanage/api/index'
import waves from '@/directive/waves' // Waves directive
import addUser from './adduser' // Secondary package based on el-pagination
import CryptoJS from '@/utils/aesJiaJM'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui

export default {
  name: 'Setadmin',
  components: { Pagination, addUser },
  directives: { waves, elDragDialog },
  props: {
    objectId: {
      type: String,
      default: () => ''
    },
    openState: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fullscreenLoading: false,
      activeName: '1',
      rolwloading: false,
      roleList: [],
      total: 0,
      dialogFormVisible: false,
      defaultProps: {
        children: 'list',
        label: 'name'
      },
      listQuery: {
        page: 1,
        limit: 10
      },
      searchOut: {
        userName: '',
        realName: '',
        phone: '',
        compatibility: []
      },
      list: [],
      listLoading: false,
      menuLoading: false,
      treeData: [],
      multipleSelection: [],
      dialogMultipleSelection: [],
      checkedData: [], // 选中的节点
      roleId: '',
      iscompatibility: 0,
      dict: {
        SFXXJR: [] // 是否向下兼容
      }
    }
  },
  watch: {
    openState(val) {
      if (val) {
        this.$nextTick(() => {
          this.getList()
        })
      }
    }
  },
  created() {
    this.getList()
    for (const key in this.dict) {
      this.getDict(key)
    }
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = response.data.data[0].list
        }).catch(error => {
          reject(error)
        })
      })
    },
    handleDecrypt(str) {
      if (str) {
        return CryptoJS.$aesJieM(str)
      } else {
        return ''
      }
    },
    /*
      * 重置用户列表搜索
    */
    handleReset() {
      this.searchOut = {
        userName: '',
        realName: '',
        phone: '',
        compatibility: []
      }
      this.getList()
    },
    /*
      * 搜索添加用户列表
    */
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getRoleList() {
      this.rolwloading = true
      return new Promise((resolve, reject) => {
        roleList().then(response => {
          this.rolwloading = false
          if (response.data.data[0]) {
            this.roleList = response.data.data[0].list
          }
        }).catch(error => {
          this.rolwloading = false
          reject(error)
        })
      })
    },
    getList(obj) {
      this.list = []
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        objectId: this.objectId || '',
        ...this.searchOut
      }
      query.phone = query.phone ? CryptoJS.$aesJiaM(query.phone) : ''
      query.compatibility = query.compatibility.length > 0 ? query.compatibility.join(',') : ''
      return new Promise((resolve, reject) => {
        userList(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },

    /*
      params: 无
      return:无
      function:获取权限树结构
    */
    getMenu() {
      this.menuLoading = true
      return new Promise((resolve, reject) => {
        queryMenu().then(response => {
          this.menuLoading = false
          this.treeData = response.data.data
        }).catch(error => {
          reject(error)
          this.menuLoading = false
        })
      })
    },
    /*
      params:原始数据
      return:无
      function：设置禁用
    */
    setNoCheck(data) {
      var vueObj = this
      if (data.length > 0) {
        data.forEach((item, i) => {
          item.disabled = true
          if (item.list && item.list.length > 0) {
            vueObj.setNoCheck(item.list)
          }
        })
      }
      return data
    },
    getRoleInfo(id, data) {
      this.setCheckedKeys(data)
      this.roleId = id
      this.getList()
    },
    /*
      params:点角色对应的code对应权限
      return:无
      params:设置树的选中与否
    */
    setTree(code) {
      var arr = code.split(',') || []
      this.checkedData = arr
    },
    /*
      params:点角色对应的code对应权限
      return:无
      params:设置树的选中与否
    */
    setCheckedKeys(code) {
      var tmp = code
      if (tmp.charAt(tmp.length - 1) === ',') {
        tmp = tmp.slice(0, tmp.length - 1)
      }
      var arr = tmp.split(',') || []
      this.$refs.tree.setCheckedKeys(arr)
    },
    handleDeletes() {
      if (this.multipleSelection.length > 0) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const arr = []
          this.multipleSelection.forEach(item => {
            arr.push(item.id)
          })
          const ids = arr.join(',')
          this.deleteUser(ids)
        }).catch(() => { })
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(row.id)
      }).catch(() => { })
    },
    deleteUser(ids) {
      return new Promise((resolve, reject) => {
        deleteUser(ids).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList()
        }).catch(error => {
          reject(error)
        })
      })
    },
    addUser() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.UserResetting.emptySelect()
        this.$refs.UserResetting.resettingall()
      })
    },
    saveData() {
      var arr = this.$refs.tree.getCheckedKeys()
      var menuIds = arr.join(',')
      this.menuLoading = true
      return new Promise((resolve, reject) => {
        saveMenu({ roleId: this.roleId, resIds: menuIds }).then(() => {
          this.menuLoading = false
          this.$message({
            message: '保存成功！',
            type: 'success'
          })
          this.getRoleList()
        }).catch(error => {
          reject(error)
          this.menuLoading = false
        })
      })
    },
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },
    /*
    * 获取子组件传过来的人员
    * */
    userData(val) {
      this.dialogMultipleSelection = val
    },
    insertUser() {
      if (!this.objectId) {
        this.$message({
          message: '请先选择选择组织！',
          type: 'warning'
        })
        return
      }
      if (this.dialogMultipleSelection.length > 0) {
        var arr = []
        this.fullscreenLoading = true
        this.dialogMultipleSelection.forEach(item => {
          arr.push(item.id)
        })
        var ids = arr.join(',')
        const query = {
          userId: ids,
          dataAuthorityType: 'SJQXLX01',
          objectId: this.objectId,
          compatibility: this.iscompatibility ? 'SFXXJR02' : 'SFXXJR01'
        }
        return new Promise((resolve, reject) => {
          insertRoleUser(query).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.fullscreenLoading = false
            this.getList()
          }).catch(error => {
            reject(error)
          })
        })
      } else {
        this.$message({
          message: '请选择用户！',
          type: 'warning'
        })
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
#setadmin {
  .search-inner-item {
    .item-label {
      margin-bottom: 10px;
    }
  }
  .leftWrap {
    .roleList {
      font-size: 14px;
      .roleitem {
        padding-left: 15px;
        height: 40px;
        line-height: 40px;
        background: #fff;
        margin-bottom: 5px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
        &.active {
          background-color: #e5e5e5;
          .playbtn {
            display: inline-block;
          }
        }
        &.roleheader {
          background: #f7f7f8;
        }
        &:hover {
          .playbtn {
            display: inline-block;
          }
        }
        span {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .rolename {
          display: inline-block;
          width: 90%;
        }
        .rolepower {
          display: inline-block;
          width: 245px;
          text-align: right;
        }
        .playbtn {
          display: none;
          cursor: pointer;
          width: 20px;
        }
      }
    }
  }
  .el-main {
    padding: 0 20px;
  }
  .powerallot-main {
    .el-tabs {
      height: 100%;
      .el-tabs__content {
        height: calc(100% - 40px);
        overflow-y: auto;
        &::-webkit-scrollbar {
          display: none;
        }
      }
      .btns {
        text-align: right;
      }
    }
    &::-webkit-scrollbar {
      display: none;
    }
  }
  .roleList,
  .leftWrap {
    &::-webkit-scrollbar {
      display: none;
    }
  }
  @keyframes antStatusProcessing {
    0% {
      transform: scale(0.8);
      opacity: 0.5;
    }
    to {
      transform: scale(2.4);
      opacity: 0;
    }
  }
}
</style>
